#!/usr/bin/python
# coding:utf-8

import os
import time
import random
from PIL import Image
import win32api, win32con, win32gui

from urllib.request import urlopen
from urllib.request import urlretrieve


def get_bing_wallpaper(save_dir=''):
    '''
    获得 bing 的壁纸
    :param save_dir: 保存路径
    :return: 壁纸的完整路径
    '''
    print('get wallpaper info.')
    root_url = 'https://www.bing.com'
    
    cn_url = root_url
    en_url = root_url + '/?ensearch=1&FORM=BEHPTB'
    url_list = [cn_url, en_url]
    
    url_index = random.randrange(len(url_list))
    print('open url' + url_list[url_index] + '...')
    
    res = urlopen(url_list[url_index]).read().decode('utf-8')

    # 查找 图片 url地址
    begin_str = 'id="bgLink" rel="preload" href="'
    begin_index = res.find(begin_str)
    if -1 == begin_index:
        print('not found wallpaper url.')
        return ''
    begin_index = begin_index + len(begin_str)

    end_str = '.jpg'
    end_index = res.find(end_str, begin_index)
    if -1 == end_index:
        print('not found wallpaper url.')
        return ''
    end_index = end_index + len(end_str)
    img_short_url = res[begin_index : end_index]
    img_name = img_short_url.replace('<', ' ').replace('>', ' ')\
                .replace('|', ' ').replace(':', ' ').replace('\"', ' ')\
                .replace('*', ' ').replace('?', ' ').replace('/', ' ')\
                .replace('\\', ' ').replace('th id=', ' ').strip()
    
    save_dir = 'C:/Users/Public/Pictures/Wallpaper/'
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
        
    img_url = root_url + img_short_url
    full_path = save_dir + img_name
    urlretrieve(img_url, filename = full_path)
    print('download wallpaper complete.')
    return full_path


def set_wallpaper_from_bmp(bmp_path):
    # 打开指定注册表路径
    reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
    # 最后的参数: 2拉伸,0居中,6适应,10填充,0平铺
    win32api.RegSetValueEx(reg_key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
    # 最后的参数: 1表示平铺,拉伸居中等都是0
    win32api.RegSetValueEx(reg_key, "TileWallpaper", 0, win32con.REG_SZ, "0")
    # 刷新桌面
    win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, bmp_path, win32con.SPIF_SENDWININICHANGE)


def set_wallpaper(img_path):
    # 把图片格式统一转换成bmp格式,并放在源图片的同一目录
    img_dir = os.path.dirname(img_path)
    bmpImage = Image.open(img_path)
    new_bmp_path = os.path.join(img_dir, 'wallpaper.bmp')
    bmpImage.save(new_bmp_path, "BMP")
    set_wallpaper_from_bmp(new_bmp_path)

if __name__ == '__main__':
    wallpaper = get_bing_wallpaper()
    if wallpaper:
        set_wallpaper(wallpaper)